package com.shoujifeng.snowmusic.player;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.ListView.XListView;
import com.shoujifeng.snowmusic.ListView.XListViewFooter;
import com.shoujifeng.snowmusic.ListView.XListView.IXListViewListener;
import com.shoujifeng.snowmusic.adapter.ListAdapter;
import com.shoujifeng.snowmusic.adapter.LoaderAdapter;
import com.shoujifeng.snowmusic.adapter.adapt;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.utils.LoadMask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;


/**
 * 在线音乐歌手内页
 * @author Administrator
 *
 */
public class OnlinePlayerContentActivity extends Activity implements IXListViewListener{
	private XListView listView;
	private LoaderAdapter mAdapter;
	private View lineLay;
	private RelativeLayout headView;
	private TextView headText;
	private ImageButton breakBtn;
	private final int UPDATE_DATA = 0;
	private ServerAccess serverAccess;
	private ArrayList<HashMap<String, Object>> mTmpList;
	private ArrayList<HashMap<String, Object>> mMusicList;
	private Thread accThread;
	private Handler mHandler;
	private int mPage = 0;
	private LoadMask mLoadMask;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.online_player_content);
		init();
		initGlobalValue();
		setListView();
		XListViewFooter.mContentView.setVisibility(View.GONE);
		mLoadMask = new LoadMask(this);
		mLoadMask.startLoad();
		accThread = new Thread(runnable);
		accThread.start();
	}
	public void init() {
		mHandler = new Handler();
		serverAccess = new ServerAccess(OnlinePlayerContentActivity.this);
		listView = (XListView) findViewById(R.id.my_collect_single_list);
		listView.setPullLoadEnable(true);
		listView.setXListViewListener(this);
		listView.setDivider(null);
		lineLay = LayoutInflater.from(OnlinePlayerContentActivity.this).inflate(R.layout.line_layout, null);
		//listView.addFooterView(lineLay);
		headView = (RelativeLayout) findViewById(R.id.headLay);
		headText = (TextView) headView.findViewById(R.id.head_text);
		breakBtn = (ImageButton) headView.findViewById(R.id.breakBtn);
		setOnClickListener();
		setListView();
		if(getIntent().getExtras().getString("name").equals("man")){
			headText.setText("藏族男歌手");
		}
		if(getIntent().getExtras().getString("name").equals("woman")){
			headText.setText("藏族女歌手");
		}
		if(getIntent().getExtras().getString("name").equals("manAndwoman")){
			headText.setText("乐队组合");
		}
	}

	private void setOnClickListener(){
		breakBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				
				overridePendingTransition(R.anim.no_move, R.anim.right_out);
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(OnlinePlayerContentActivity.this,OnlinePlayerContentListActivity.class);
				intent.putExtra(ServerAccess.INDEX, mMusicList.get(position).get(ServerAccess.INDEX).toString());
				intent.putExtra(ServerAccess.SINGER, mMusicList.get(position).get(ServerAccess.SINGER).toString());
				startActivity(intent);
				 
				overridePendingTransition(R.anim.bottom_in,android.R.anim.fade_out);
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		{
			finish();
			
			overridePendingTransition(R.anim.no_move, R.anim.right_out);
		}
			break;

		default:
			break;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	private void setListView() {
		mMusicList = new ArrayList<HashMap<String, Object>>();
		
		String[] keys = new String[] { ServerAccess.SINGER};
		mAdapter = new LoaderAdapter(this, mMusicList, new int[] {
				R.id.playerName }, keys,
				new String[] { ServerAccess.ICON_URL },
				new int[] { R.id.face }, R.drawable.icon_singer_default,
				R.layout.online_player_content_list);
		listView.setAdapter(mAdapter);
	}
	private void initGlobalValue() {
		GlobalValue.initSDAddr();

		GlobalValue.addUrl(ServerAccess.SINGER_LIST,
				"http://www.snowmusic.com.cn/mobile_api/singer_list.php");
	}

	protected Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case UPDATE_DATA: {
				mLoadMask.stopLoad();
				XListViewFooter.mContentView.setVisibility(View.VISIBLE);
				updateArrayList();
			}
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	// 创建多线程获取数据
	protected Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				SharedPreferences spf = PreferenceManager.getDefaultSharedPreferences(OnlinePlayerContentActivity.this);
				   String value = spf.getString(ServerAccess.SET_WIFI, "");   //参数: 1-要读出的键值  2- 默认值(就是读取失败后返回的值)
				   boolean setWifi = ServerAccess.checkNetworkConnection(OnlinePlayerContentActivity.this);
				if(value.equals("yes")&&setWifi){
					String[] keys = new String[] { ServerAccess.SINGER,ServerAccess.INDEX,ServerAccess.ICON_URL};
					mTmpList = new ArrayList<HashMap<String, Object>>();
					String index = "";
					if(getIntent().getExtras().getString("name").equals("man")){
						index = "0";
					}
					if(getIntent().getExtras().getString("name").equals("woman")){
						index = "1";
					}
					if(getIntent().getExtras().getString("name").equals("manAndwoman")){
						index = "2";
					}
					mTmpList = serverAccess.getSingerListByState(keys,index,mPage);
					
					sendMessage(UPDATE_DATA);
				}
				if(value.equals("no")||setWifi){
					String[] keys = new String[] { ServerAccess.SINGER,ServerAccess.INDEX,ServerAccess.ICON_URL};
					mTmpList = new ArrayList<HashMap<String, Object>>();
					String index = "";
					if(getIntent().getExtras().getString("name").equals("man")){
						index = "0";
					}
					if(getIntent().getExtras().getString("name").equals("woman")){
						index = "1";
					}
					if(getIntent().getExtras().getString("name").equals("manAndwoman")){
						index = "2";
					}
					mTmpList = serverAccess.getSingerListByState(keys,index,mPage);
					
					sendMessage(UPDATE_DATA);
				}
				

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	};

	// 发送消息到Handler
	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	// 若在线程中更新与Adapter的动态数组将会产生致命错误。
	private void updateArrayList() {

		if (mMusicList != null) {
			int count = mTmpList.size();
			for (int i = 0; i < count; i++) {
				mMusicList.add(mTmpList.get(i));
			}

			 mTmpList.clear();
			 mTmpList = null;
		}

		mAdapter.notifyDataSetChanged();
	}
	private void onLoad() {
		listView.stopRefresh();
		listView.stopLoadMore();
		listView.setRefreshTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	}


	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub

		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				mPage = mPage+1;
				accThread = new Thread(runnable);
				accThread.start();
				onLoad();
			}
		}, 1000);
		
	}
}
